import 'package:camera/camera.dart';
import 'package:enterprise_v6_app/app/components/custom_app_bar.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/widget_extension.dart';
import 'package:enterprise_v6_app/app/modules/auth/face/face_controller.dart';
import 'package:enterprise_v6_app/app/modules/auth/face/model.dart';

/// 调用示例
/// Get.toNamed(AppRoutes.faceAuth);
/// 从此页面返回，会返回一个 bool?
/// - true：成功
/// - false：失败
/// - null：未识别
class FaceAuthPage extends StatelessWidget {
  FaceAuthPage({super.key});

  final ctrl = Get.put(FaceAuthController());

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: GetBuilder(
        init: ctrl,
        builder: (_) {
          return Scaffold(
            appBar: CustomAppBar(
              titleText: '人脸识别',
              showAlarmButton: false,
            ),
            body: _buildBody(),
          );
        },
      ),
      onWillPop: () async {
        // AppToast.showWarning('请进行身份认证!');
        Get.back(result: ctrl.suc);
        return false;
      },
    );
  }

  Widget _buildBody() {
    switch (ctrl.status) {
      case FaceAuthStatus.before:
        return _buildAuthBefore();
      case FaceAuthStatus.noPerm:
        return _buildAuthNoPerm();
      case FaceAuthStatus.ing:
        return _buildAuthing();
      case FaceAuthStatus.success:
        return _buildAuthSuccess();
      case FaceAuthStatus.failed:
        return _buildAuthFail();
      case null:
        return const Center(
          child: CircularProgressIndicator(),
        );
    }
  }

  /// 页面骨架
  Widget _buildBodyScaffold(Widget top, Widget center, Widget bottom) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          AppGaps.vGap100,
          top,
          AppGaps.vGap20,
          center,
          AppGaps.vGap50,
          bottom,
        ],
      ),
    );
  }

  /// 没有权限
  Widget _buildAuthNoPerm() {
    return _buildBodyScaffold(
      Image.asset(
        AppImages.face_auth_fail,
        height: 150.w,
        width: 150.w,
      ),
      _buildText('请允许摄像头权限'),
      _buildBtn('刷新权限', ctrl.refreshPerm),
    );
  }

  /// 有权限，点击按钮开始识别
  Widget _buildAuthBefore() {
    return _buildBodyScaffold(
      _buildCameraCircle(),
      _buildText('请保持光线充足、正视屏幕、面部无遮挡'),
      _buildBtn('拍照', ctrl.capture),
    );
  }

  /// 识别中
  Widget _buildAuthing() {
    return _buildBodyScaffold(
      _buildCameraCircle(),
      _buildText('请保持光线充足'),
      _buildBtn('开始验证', ctrl.startAuth),
    );
  }

  /// 识别成功
  Widget _buildAuthSuccess() {
    return _buildBodyScaffold(
      Image.asset(
        AppImages.face_auth_success,
        height: 150.w,
        width: 150.w,
      ),
      _buildText('认证成功\n恭喜您完成了身份验证'),
      _buildBtn('返回', () {
        Get.back(result: true);
      }),
    );
  }

  /// 识别失败
  Widget _buildAuthFail() {
    return _buildBodyScaffold(
      Image.asset(
        AppImages.face_auth_fail,
        height: 150.w,
        width: 150.w,
      ),
      _buildText('认证失败'),
      _buildBtn('再次尝试', () {
        ctrl.status = FaceAuthStatus.before;
        ctrl.image = null;
        ctrl.update();
      }),
    );
  }

  Widget _buildText(String text) {
    return Text(
      text,
      style: TextStyle(fontSize: 14.w, color: const Color(0xFFB3B3B3)),
      textAlign: TextAlign.center,
    );
  }

  Widget _buildBtn(String text, void Function() onTap) {
    return Container(
      decoration: BoxDecoration(
        color: const Color(0xFF5C6DFF),
        borderRadius: BorderRadius.circular(27.w),
      ),
      width: 307.w,
      height: 40.w,
      child: Center(
          child: Text(
        text,
        style: TextStyle(fontSize: 16.w, color: Colors.white),
      )),
    ).clickOnce(onTap);
  }

  Widget _buildCameraCircle() {
    final child = ctrl.image == null
        ? _buildCamera()
        : Image.memory(
            ctrl.image!,
            fit: BoxFit.cover,
          );
    return SizedBox(
      width: Get.width * 0.77,
      child: ClipRRect(borderRadius: BorderRadius.circular(37.w), child: child),
    );
  }

  Widget? _buildCamera() {
    if (ctrl.camera == null) {
      return null;
    }
    return Stack(
      alignment: Alignment.center,
      children: [
        CameraPreview(ctrl.camera!),
        SvgPicture.asset(
          AppImages.face_mask,
          width: 300.w,
          height: 300.w,
        ),
      ],
    );
  }
}
